package com.trial.eyefollowupapp.screens

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.scaleOut
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.*
import androidx.navigation.NavHostController
import com.trial.eyefollowupapp.R
import com.trial.eyefollowupapp.RetrofitClient
import com.trial.eyefollowupapp.theme.AppAnimations
import com.trial.eyefollowupapp.theme.AppDimens
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import androidx.compose.foundation.background

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginScreen(navController: NavHostController) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }
    var errorMsg by remember { mutableStateOf("") }
    var loading by remember { mutableStateOf(false) }
    var triggerLogin by remember { mutableStateOf(false) }
    var showForm by remember { mutableStateOf(false) }

    // Initial animation
    LaunchedEffect(Unit) {
        showForm = true
    }

    // Login logic
    LaunchedEffect(triggerLogin) {
        if (triggerLogin) {
            try {
                val response = withContext(Dispatchers.IO) {
                    RetrofitClient.instance.login(username, password)
                }

                loading = false
                triggerLogin = false
                if (response.isSuccessful) {
                    val loginResponse = response.body()
                    if (loginResponse != null) {
                        // Navigate to home on success
                        navController.navigate("home/${username}")
                        errorMsg = ""
                    } else {
                        errorMsg = "登录响应为空"
                    }
                } else {
                    errorMsg = "用户名或密码错误"
                }
            } catch (e: Exception) {
                loading = false
                triggerLogin = false
                errorMsg = "网络请求失败: ${e.message}"
            }
        }
    }

    Scaffold(
        modifier = Modifier.fillMaxSize(),
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(MaterialTheme.colorScheme.background)
                .padding(horizontal = AppDimens.spacingXLarge),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // App logo
            AnimatedVisibility(
                visible = showForm,
                enter = scaleIn(
                    initialScale = 0.8f,
                    animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                ),
                exit = scaleOut(
                    targetScale = 0.8f,
                    animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                )
            ) {
                Image(
                    painter = painterResource(id = R.drawable.cover),
                    contentDescription = null,
                    modifier = Modifier
                        .size(180.dp)
                        .padding(bottom = AppDimens.spacingLarge)
                )
            }

            // Title
            AnimatedVisibility(
                visible = showForm,
                enter = fadeIn(
                    animationSpec = tween(
                        durationMillis = AppAnimations.durationMedium,
                        delayMillis = 100
                    )
                ),
                exit = fadeOut(
                    animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                )
            ) {
                Text(
                    "眼底随访系统",
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary,
                    modifier = Modifier.padding(bottom = AppDimens.spacingXLarge)
                )
            }

            // Form area
            Column(
                modifier = Modifier.fillMaxWidth(),
                verticalArrangement = Arrangement.spacedBy(AppDimens.spacingMedium)
            ) {
                // Username field
                AnimatedVisibility(
                    visible = showForm,
                    enter = fadeIn(
                        animationSpec = tween(
                            durationMillis = AppAnimations.durationMedium,
                            delayMillis = 200
                        )
                    ),
                    exit = fadeOut(
                        animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                    )
                ) {
                    OutlinedTextField(
                        value = username,
                        onValueChange = { username = it },
                        label = { Text("用户名") },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(AppDimens.cornerRadiusMedium),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline
                        )
                    )
                }

                // Password field
                AnimatedVisibility(
                    visible = showForm,
                    enter = fadeIn(
                        animationSpec = tween(
                            durationMillis = AppAnimations.durationMedium,
                            delayMillis = 300
                        )
                    ),
                    exit = fadeOut(
                        animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                    )
                ) {
                    OutlinedTextField(
                        value = password,
                        onValueChange = { password = it },
                        label = { Text("密码") },
                        visualTransformation = PasswordVisualTransformation(),
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(AppDimens.cornerRadiusMedium),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = MaterialTheme.colorScheme.primary,
                            unfocusedBorderColor = MaterialTheme.colorScheme.outline
                        )
                    )
                }

                // Error message
                AnimatedVisibility(
                    visible = errorMsg.isNotEmpty(),
                    enter = fadeIn(
                        animationSpec = tween(durationMillis = AppAnimations.durationShort)
                    ),
                    exit = fadeOut(
                        animationSpec = tween(durationMillis = AppAnimations.durationShort)
                    )
                ) {
                    Text(
                        errorMsg,
                        color = MaterialTheme.colorScheme.error,
                        modifier = Modifier.padding(top = AppDimens.spacingSmall)
                    )
                }

                // Login button
                AnimatedVisibility(
                    visible = showForm,
                    enter = fadeIn(
                        animationSpec = tween(
                            durationMillis = AppAnimations.durationMedium,
                            delayMillis = 400
                        )
                    ),
                    exit = fadeOut(
                        animationSpec = tween(durationMillis = AppAnimations.durationMedium)
                    )
                ) {
                    Button(
                        onClick = {
                            if (username.isBlank() || password.isBlank()) {
                                errorMsg = "用户名和密码不能为空"
                                return@Button
                            }

                            loading = true
                            triggerLogin = true
                        },
                        shape = RoundedCornerShape(AppDimens.cornerRadiusMedium),
                        modifier = Modifier.fillMaxWidth(),
                        enabled = !loading,
                        elevation = ButtonDefaults.buttonElevation(
                            defaultElevation = AppDimens.elevationMedium,
                            pressedElevation = AppDimens.elevationLarge
                        )
                    ) {
                        if (loading) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(18.dp),
                                color = MaterialTheme.colorScheme.onPrimary
                            )
                        } else {
                            Text(
                                "登录",
                                fontSize = 16.sp,
                                modifier = Modifier.padding(vertical = AppDimens.spacingSmall)
                            )
                        }
                    }
                }

        }
    }
}
    }
